package com.gitee.aleenjava.aliyun.mqtt.service.client;

import com.gitee.aleenjava.aliyun.mqtt.config.MqttPublisherProperties;
import com.gitee.aleenjava.aliyun.mqtt.processor.MqttPublishProcessor;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.nio.charset.StandardCharsets;

/**
 * 消息发布处理器实现类
 *
 * @author cheng
 */
public class MqttPublishProcessorImpl implements MqttPublishProcessor {

    private final MqttPublisherProperties mqttPublisherProperties;

    private final MqttPublishClient mqttPublishClient;

    public MqttPublishProcessorImpl(MqttPublisherProperties mqttPublisherProperties, MqttPublishClient mqttPublishClient) {
        this.mqttPublisherProperties = mqttPublisherProperties;
        this.mqttPublishClient = mqttPublishClient;
    }

    @Override
    public void publish(String topic, MqttMessage message) throws MqttException {
        mqttPublishClient.publish(topic, message);
    }

    @Override
    public void publish(String topic, String message) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(message.getBytes(StandardCharsets.UTF_8));
        mqttMessage.setRetained(true);
        mqttMessage.setQos(mqttPublisherProperties.getQos());
        mqttPublishClient.publish(topic, mqttMessage);
    }

    @Override
    public void publish(String topic, byte[] message) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(message);
        mqttMessage.setRetained(true);
        mqttMessage.setQos(mqttPublisherProperties.getQos());
        mqttPublishClient.publish(topic, mqttMessage);
    }
}
